var pagenavigation = new PageNavigation;
var persistence = new Persistence();
$(document).ready(function(){
   pagenavigation.goToHome(homeLoaded);
   siteStack.push('home.html');
});
var currentSite = "";
$(document).on('click', '.onClickGoToHome', function(){
   pagenavigation.goToHome(homeLoaded);
   currentSite = "home.html";
});

var siteStack = [];
$(document).on('click', '.onClickGoBack', function(){
    var backSite = siteStack.pop();
    
    if(backSite == "home.html" || backSite == "home2.html"){
        functionCall = homeLoaded;
    }else if(backSite == "group.html"){
        functionCall = groupLoaded;
    }else if(backSite == "match.html"){
        functionCall = matchLoaded;
    }
    pagenavigation.goTo(backSite, functionCall);
});

var currClickedGroupId = 0;
var currClickedGroupOrderId = 0;
var currClickedGroupName = "";
$(document).on('click', '.onClickGoToGroup', function(){
    currClickedGroupId = $(this).find('.groupId').val();
    currClickedGroupOrderId = $(this).find('.groupOrderId').val();
    currClickedGroupName = $(this).find('.groupName').val();
    siteStack.push(currentSite);
    pagenavigation.goTo('group.html', groupLoaded);
   
});

var currClickedMatchId = 0;
$(document).on('click', '.onClickGoToMatch', function(){
    currClickedMatchId = $(this).find('.matchId').val();
    siteStack.push(currentSite);
    pagenavigation.goTo('match.html', matchLoaded); 
});

$(document).swipe({
  swipe:function(event, direction, distance, duration, fingerCount) {
    if(direction == "left"){
        siteStack.push(currentSite);
        pagenavigation.swipeLeft(homeLoaded);
    }
    if(direction == "right"){
        siteStack.push(currentSite);
        pagenavigation.swipeRight(homeLoaded);
    }
  }
});

function homeLoaded(e){
  html = $.parseHTML(e);
  var homescreentype = "1";
  $.each(html, function(key, value){
      if($(value).attr('id') == "homescreentype"){
          homescreentype = $(value).val();
      }
  });
  switch(homescreentype){
      case '1':
          persistence.getallGroupsForWM2014(function(arrGroups){
              for(var key in arrGroups){
                  var html = "<tr>";
                      html += "<td class='onClickGoToGroup'>"; 
                      html += "<input type='hidden' class='groupId' value='" + arrGroups[key].getGroupId() + "'>";
                      html += "<input type='hidden' class='groupOrderId' value='" + arrGroups[key].getGroupOrderId() + "'>";
                      html += "<input type='hidden' class='groupName' value='" + arrGroups[key].getGroupName() + "'>";
                      html += "<span class='left'><i class='fa fa-bars'></i></span>";
                      html += arrGroups[key].getGroupName() + "</td>";
                      html += "</tr>";
                  $('#grouplist').find('tbody').append(html);
              }
          });

          /* Add contact information. */
          contact_information =
              "<br>" +
              "<div id=\"contact\">" +
                "Copyright 2014: Temmel Philipp, Dulzky Florian<br>" +
                "Kontakt: Philipp.Temmel@edu.fh-joanneum.at bzw. Florian.Dulzky@edu.fh-joanneum.at" +
              "</div>";

          $('#grouplist').find('tbody').append(contact_information);

          $('.headline').html('WM-App 2014: Gruppenübersicht');
          currentSite = "home.html";
          break;
      case '2':
          $('#calendar').fullCalendar({
              dayClick: function(date) {
                $('.fc-day').each(function(){
                    $(this).css('background-color', 'none');
                });
                $(this).css('background-color', '#58B3F0');

                persistence.getAllMatchesForSelectedDate(date.format(), function(arrMatches){
                    parseMatchesInTable(arrMatches);
                });
              }
          });
          currentSite = "home2.html";
          $('.headline').html('WM-App 2014: Matchtagübersicht');
          break;
  }
}

function groupLoaded(){
    persistence.getGroupById(currClickedGroupId, currClickedGroupOrderId, currClickedGroupName, function(group){
        $('#pagetitle').html(group.getGroupName());
        var teams = group.getAllTeams();
        $('#teamlist').find('tbody').html('');
        $.each(teams, function(key, value){
            var html = "<tr>";
                html += "<td>" + value.getName() + "</td>";
                html += "<td>" + group.getScoreForTeam(value.getName()) + "</td>";
                html += "</tr>";
            $('#teamlist').find('tbody').append(html);
        });
        var matches = group.getAllMatches();
        parseMatchesInTable(matches);
        currentSite = "group.html";
        $('.headline').html('WM-App 2014: Gruppendetailansicht');
    });
}

function matchLoaded(){
    persistence.getMatchByMatchId(currClickedMatchId, function(match){
        $('#teamName1').html(match.getTeam1());
        $('#teamName2').html(match.getTeam2());
        var pointsT1 = match.getTeam1Points();
        pointsT1 = pointsT1 == -1 ? '-' : pointsT1;
        $('#scoreTeam1').html(pointsT1);
        var pointsT2 = match.getTeam2Points();
        pointsT2 = pointsT2 == -1 ? '-' : pointsT2;
        $('#scoreTeam2').html(pointsT2);
        
        var goals = match.getGoals();
        $.each(goals, function(key, value){
            var html = "<tr>";
                html += "<td>" + value.getGoalMatchMinute(); + "</td>";
                scorerTeam = "";
                if(value.getWhichTeamScoredCurrentGoal() == 1){
                  scorerTeam = match.getTeam1();
                }else{
                  scorerTeam = match.getTeam2();
                }
                html += "<td>TOOOR: " + scorerTeam + " (" + value.getGoalGetterName() + ")" + "</td>";
                html += "</tr>";
                $('#goals').find('tbody').append(html);
        });
        initialize(match.getCity());
        currentSite = "match.html";
        $('.headline').html('WM-App 2014: Match');
    });
}

function parseMatchesInTable(arrMatches){
    $('#matchlist').find('tbody').html('');
    $.each(arrMatches, function(key, value){
        var html = "<tr class='onClickGoToMatch'>";
            html += '<input type="hidden" class="matchId" value="' + arrMatches[key].getId() + '">';
            html += "<td>" + arrMatches[key].getStartDateTime().replace("T", " ") +"</td>";
            html += "<td>" + arrMatches[key].getTeam1() +"</td>";
            html += "<td>" + arrMatches[key].getTeam2() +"</td>";
            var pointsT1 = arrMatches[key].getTeam1Points();
            pointsT1 = pointsT1 == "-1" ? "-" : pointsT1;
            var pointsT2 = arrMatches[key].getTeam2Points();
            pointsT2 = pointsT2 == "-1" ? "-" : pointsT2;
            html += "<td>" + pointsT1 + " : " + pointsT2 + "</td>";
            html += "</tr>";
        $('#matchlist').find('tbody').append(html);
    });
}


function initialize(matchCity) {
  var mapOptions = {
    zoom: 2
  };
  map = new google.maps.Map(document.getElementById('map'),
      mapOptions);

  // Try HTML5 geolocation
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var myPos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);
                           
   
      
                                     

      var infowindow = new google.maps.InfoWindow({
        map: map,
        position : myPos,
        content: 'You are here ;) '
      });
      
      var geo = new google.maps.Geocoder;

      geo.geocode({'address':matchCity},function(results, status){
              var matchPos = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
              if (status == google.maps.GeocoderStatus.OK) {
                    var infowindow2 = new google.maps.InfoWindow({
                        map: map,
                        position : matchPos,
                        content: 'The match is here. (' + matchCity + ')'
                    });
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }
       });
      
      

      map.setCenter(myPos);
    });
  } else {
    document.getElementById('map-canvas').innerHTML = "Gelocation not available";
  }
}
